package com.shuoyutech.dp.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

/**
 * 文件工具
 */
@Slf4j
public class FileUtils {

    public static void deleteFile(List<String> filePathList) {
        if (CollectionUtils.isEmpty(filePathList)) return;
        for (String filePath : filePathList) {
            File file = new File(filePath);
            boolean flag = file.delete();
            log.info("{} 文件是否删除 {}", filePath, flag);
        }
    }

    /**
     * 文件下载
     * @param response
     * @param filePath
     */
    @SuppressWarnings("Duplicates")
    public static void downloadExcel(HttpServletResponse response, String filePath) throws IOException {
        // 设置请求
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filePath, "UTF-8"));
        // 打开流
        File file = new File(filePath);
        if (!file.exists()) return;
        FileInputStream fis = null;
        // 输出文件
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        try {
            fis = new FileInputStream(file);
            int length;
            byte[] buffer = new byte[1024];
            while ((length = fis.read(buffer)) != -1) {
                bos.write(buffer, 0, length);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(fis);
            IOUtils.closeQuietly(bos);
        }
    }

    @SuppressWarnings("Duplicates")
    public static void downloadExcel(HttpServletResponse response, InputStream fis, String fileName) throws IOException {
        if (Objects.isNull(fis)) return;
        // 设置请求
        response.setContentType("application/octet-stream;charset=UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        // 输出文件
        BufferedInputStream bis = new BufferedInputStream(fis);
        BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
        try {
            int length;
            byte[] buffer = new byte[1024];
            while ((length = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, length);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(bis);
            IOUtils.closeQuietly(bos);
        }
    }
}
